<?php

namespace app\controller\backend;

use app\model\Poster;
use Kkokk\Poster\PosterManager;

class PosterController extends BaseController
{
    public function index()
    {
        $posterModel = new Poster();
        return json($posterModel->getPosterList([]));
    }

    public function add()
    {
        if (request()->isPost()) {
            $param = input('post.');
            $param['id'] = $param['id'] ?? 0;

            if (empty($param['name'])) {
                return jsonReturn(-1, lang('请填写海报名称'));
            }
            $posterModel = new Poster();
            if ($posterModel->where([
                ['id', '<>', $param['id']],
                ['name', '=', $param['name']]
            ])->value('id')) {
                return jsonReturn(-1, lang('海报名称已存在'));
            }

            try {
                $preview = $this->makePreview($param, 'cover');
            } catch (\Exception $e) {
                return jsonReturn(-3, 'error', $e->getTrace());
            }

            $addParam = [
                'name' => $param['name'],
                'preview' => request()->domain() . '/' . ltrim($preview['url'], './'),
                'status' => 1,
                'design_content' => json_encode($param)
            ];

            if (!empty($param['id'])) {
                return json($posterModel->editPoster([['id', '=', $param['id']]],$addParam));
            }

            return json($posterModel->addPoster($addParam));
        }
    }

    public function copy() {
        if (!request()->isPost()) {
            return jsonReturn(-1, lang('请求错误'));
        }

        $param = input('post.');
        if (empty($param['id'])) {
            return jsonReturn(-2, lang('参数错误'));
        }
        $posterModel = new Poster();
        $data = $posterModel->where('id', '=', $param['id'])->findOrEmpty();
        if (empty($data)) {
            return jsonReturn(-3, lang('找不到要复制的海报'));
        }

        $designContent = json_decode($data['design_content'], true);

        $designContent['name'] = $designContent['name'] . lang('-副本');
        unset($designContent['id']);
        $addParam = [
            'name' => $designContent['name'],
            'preview' => $data['preview'],
            'status' => 1,
            'design_content' => json_encode($designContent)
        ];
        $res = $posterModel->addPoster($addParam);
        if ($res['code'] == 0) {
            $res['msg'] = lang('复制成功');
        }
        return json($res);
    }

    public function edit()
    {
        $id = input('param.id');

        $posterModel = new Poster();
        return json($posterModel->getDesignInfoById($id));
    }

    public function del()
    {
        $id = input('param.id');

        $posterModel = new Poster();
        return json($posterModel->del($id));
    }

    public function preview()
    {
        try {

            $posterData = input('post.');
            $result = $this->makePreview($posterData);

            return jsonReturn(0, 'success', request()->domain() . '/' . ltrim($result['url'], './'));
        } catch (\Exception $e) {
            file_put_contents('./error.log', $e->getFile() . ' --- ' . $e->getLine() . ' --- ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            return jsonReturn(-1, $e->getMessage());
        }
    }

    /**
     * @param $posterData
     * @param $type
     * @return mixed
     */
    protected function makePreview($posterData, $type = 'temp')
    {
        $name = uniqid();

        if ($type == 'temp') {
            $PosterManager = new PosterManager('./poster_preview/temp/' . $name . '.' . $posterData['type']);
        } else {
            $PosterManager = new PosterManager('./poster_preview/cover/' . $name . '.' . $posterData['type']);
        }

        $temp = $PosterManager;

        if ($posterData['activeName'] == 'img' && !empty($posterData['img_src'])) {
            $temp = $temp->buildImDst($posterData['img_src'], $posterData['width'], $posterData['height']);
        } else {
            $temp = $temp->buildIm($posterData['width'], $posterData['height'], $this->hex2rgba($posterData['color']));
        }

        if (isset($posterData['item']) && !empty($posterData['item'])) {
            foreach ($posterData['item'] as $vo) {
                if ($vo['t'] == 'text') {
                    $font = '/system_file/alifont/' . $vo['fn'] . '.woff';
                    $temp = $temp->buildText($vo['v'], $vo['x'], $vo['y'], $vo['s'], $this->hex2rgba($vo['c']), $vo['w'], $font, $vo['a'], $vo['w'], 1, 0, $vo['rotate']);
                } else if ($vo['t'] == 'image') {
                    $temp = $temp->buildImage($vo['v'], $vo['x'], $vo['y'], 0, 0, $vo['w'], $vo['h'], $this->hex2rgba($vo['c']), 'normal', $vo['rotate']);
                } else if ($vo['t'] == 'qrcode') {
                    $temp = $temp->buildQr($vo['v'], $vo['x'], $vo['y'], 0, 0, $vo['w'], $vo['h'], 4, 1, $vo['rotate']);
                }
            }
        }

        return $temp->getPoster();
    }

    protected function hex2rgba($color)
    {
        $hexColor = str_replace('#', '', $color);
        $lens = strlen($hexColor);

        if ($lens != 3 && $lens != 6) {
            return false;
        }

        $newColor = '';
        if ($lens == 3) {

            for ($i = 0; $i < $lens; $i++) {
                $newColor .= $hexColor[$i] . $hexColor[$i];
            }
        } else {

            $newColor = $hexColor;
        }

        $hex = str_split($newColor, 2);
        $rgba = [];

        foreach ($hex as $vls) {
            $rgba[] = hexdec($vls);
        }

        $rgba[] = 1;
        return $rgba;
    }
}
